package com.gwt.mvp.sample.client.presenter;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.gwt.mvp.connection.dispatcher.shared.Dispatcher;
import com.gwt.mvp.sample.client.event.ResetViewEvent;
import com.gwt.mvp.sample.shared.action.IncrementCounterAction;
import com.gwt.mvp.sample.shared.model.Entity;
import com.gwt.mvp.sample.shared.result.IntegerResult;

public class EntityPresenter implements Presenter {

	private Entity entity;
	
	public interface Display {
	    public HasClickHandlers getIncrementButton();
	    public HasClickHandlers getResetViewButton();
	    public void setData(Integer data);
	    public Widget asWidget();
	}
	
	private final HandlerManager eventBus;
	private final Display display;
	
	
	public EntityPresenter(HandlerManager eventBus, Display display) {
		this.eventBus = eventBus;
		this.display = display;
	}

	public void bind(){
		display.getIncrementButton().addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				incrementEntityValue();
			}
		});
		
		display.getResetViewButton().addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new ResetViewEvent());
			}
		});
	}

	@Override
	public void go(HasWidgets container) {
		bind();
	    container.clear();
	    container.add(display.asWidget());
	    initializeEntity();
	}

	private void initializeEntity() {
		entity = new Entity(0);
	}

	/**
	 * Test method, it should be fetched from the server using the Dispatcher
	 */
	private void incrementEntityValue() {
		Dispatcher.execute(new IncrementCounterAction(entity.getValue()), new AsyncCallback<IntegerResult>(){

			@Override
			public void onFailure(Throwable caught) {
				GWT.log("Error trying to increment the entity's value");
			}

			@Override
			public void onSuccess(IntegerResult result) {
				entity.setValue(result.getValue());
				display.setData(result.getValue());
			}
			
		});
		
	}

}
